package org.zxp.thread.hang;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * @program: zxp-thread-test
 * @description: ${description}
 * @author: X-Pacific zhang
 * @create: 2019-05-07 16:33
 **/
public class WaitTest {
    @Test
    public void testWait(){
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(() -> {
            synchronized (WaitTest.class) {
                System.out.println("Thread1");
                try {
                    System.out.println("Thread1准备阻塞");
                    // 调用wait()方法，Thread1挂起（等待唤醒），并把锁交给Thread2
                    WaitTest.class.wait();
                    System.out.println("Thread1解除阻塞");
                    Thread.sleep(500L);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("Thread1完成");
                //调用notify()方法，通知唤醒Thread2，不释放锁（锁还在自己身上）
                WaitTest.class.notify();
                countDownLatch.countDown();
            }//执行完成synchronized，释放锁，即使释放了锁，不调用notify，Thread2的wait()也无法被唤醒
        }).start();

        new Thread(() -> {
            synchronized (WaitTest.class) {
                System.out.println("Thread2");
                try {
                    //调用notify()方法，通知唤醒Thread1，不释放锁（锁还在自己身上）
                    WaitTest.class.notify();
                    Thread.sleep(500L);
                    System.out.println("Thread2准备阻塞");
                    // 调用wait()方法，Thread2挂起（等待唤醒），并把锁交给Thread1
                    WaitTest.class.wait();
                    System.out.println("Thread2解除阻塞");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("Thread2完成");
                countDownLatch.countDown();
            }
        }).start();

        while (true){
           if( countDownLatch.getCount() == 0){
               return;
           }
        }
    }
}
